package
{
	//import com.adobe.crypto.HMAC;
	//import com.adobe.crypto.SHA256;
	
	import mx.controls.*;
	import mx.rpc.events.*;
	
	/**
	 * 
	 */
	public class CallWithLogin implements IStrategy
	{
		
		private var ui:DruplexEngine;
		
		[Bindable] private var testResult:Array;
		private var apiKey:String = "e1e47715584eeb0f50f113fa4a1291ee";
		private var apiDomain:String = "www.bonmotter.com/drupal";
		private var sessionID:String;
		private var currentUser:String;
		private var userName:String = "testUser";
		private var userPass:String = "testPswd";
		
		
		////////////////////////////////////////////////////////////////////////////////
		//
		// IStrategy API
		//
		////////////////////////////////////////////////////////////////////////////////
		
		public function execute(ui:DruplexEngine):void
		{
			this.ui = ui;
			start();
		}
		
		public function onSystemConnect(event:ResultEvent):void
		{
			sessionID = event.result.sessid;
			currentUser = event.result.user.name;
			
			if(event.result.user.roles["2"] == "authenticated user")
			{
				getNode();
			}
			else
			{
				loginUser();
			}
		}
		
		public function onUserLogin(event:ResultEvent):void
		{
			getNode();
		}
		
		////////////////////////////////////////////////////////////////////////////////
		//
		// PROTECTEDS
		//
		////////////////////////////////////////////////////////////////////////////////
		
		protected function start():void
		{
			ui.system.connect();
		}
		
		/**
		 * userName and userPass will normally come from a login form,
		 * but here we login automatically for testing purposes
		 */
		protected function loginUser():void
		{
			var hashedArray:Array = hashKey("user.login");
			ui.user.login(hashedArray[0], hashedArray[1], hashedArray[2], hashedArray[3], sessionID, userName, userPass);
		}
		
		protected function getNode():void
		{
			ui.node.get(sessionID, 1);
		}
		
		protected function hashKey(serviceMethod:String):Array
		{
			var captureTime:String = (Math.round((new Date().getTime())/1000)).toString();
			var captureRandom:String = randomString(10);
			var hashString:String = captureTime + ";";
			hashString += apiDomain + ";";
			hashString += captureRandom + ";";
			hashString += serviceMethod;
			return null;
			//return [HMAC.hash(apiKey, hashString, SHA256), apiDomain, captureTime, captureRandom];
		}
		
		protected function randomString(Stringlength:Number):String
		{
			var allowedChar:String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
			var allowedArray:Array = allowedChar.split("");
			var randomChars:String = "";
			for (var i:Number = 0; i < Stringlength; i++)
			{
				randomChars += allowedArray[Math.floor(Math.random() * allowedArray.length)];
			}
			return randomChars;
		}
	}
}